﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using Vacation.DAL;
using Vacation.Models;
using System.Web.Security;
using System.Data.SqlClient;
using System.Data;

namespace Vacation.Controllers
{
    public class AdminController : Controller
    {
        string connectionString;

        #region 连接数据库
        public AdminController()
        {
            ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings["Vacation"];

            if ((ConnectionStringSettings == null) || (ConnectionStringSettings.ConnectionString.Trim() == String.Empty))
            {
                throw new Exception("连接字符串为空");
            }
            connectionString = ConnectionStringSettings.ConnectionString;
        }
        #endregion

        //用户列表页
        //GET admin/UserIndex?realname=?&school=%
         [Authorize(Roles="系统管理员")]
        public ActionResult UserIndex(string realname,string school, int? page)
        {
            // int iRecordCount = 0;
            page = page ?? 1;
            realname = realname ?? "%";
            school = school ?? "%";

            int total = 0;//总数
            int pagesize = 0;//页大小
            int pagecount = 0;

            List<UserListModel> Users = new List<UserListModel>();
            UserListModel user = null;

            SqlConnection sqlConnection = new SqlConnection(connectionString);
            SqlCommand sqlCommand = new SqlCommand("Teachers_Sel", sqlConnection);
            sqlCommand.CommandType = CommandType.StoredProcedure;

            SqlDataReader sqlDataReader = null;
            try
            {
                sqlCommand.Parameters.Add("@page", SqlDbType.Int).Value = page;
                sqlCommand.Parameters.Add("@name", SqlDbType.NVarChar, 60).Value = realname;
                sqlCommand.Parameters.Add("@school", SqlDbType.NVarChar, 2).Value = school;

                sqlConnection.Open();
                //默认会返回
                sqlDataReader = sqlCommand.ExecuteReader();

                if (sqlDataReader.HasRows)
                {
                    sqlDataReader.Read();
                    total = Convert.ToInt32(sqlDataReader["amount"]);
                    pagesize = Convert.ToInt32(sqlDataReader["pagesize"]);
                }
                sqlDataReader.NextResult();
                while (sqlDataReader.Read())
                {
                    user = new UserListModel();
                    user.UserName = sqlDataReader["TeacherNo"].ToString();
                    user.RealName = sqlDataReader["Name"].ToString();
                    user.School = sqlDataReader["School"].ToString();
                    Users.Add(user);
                }
                pagecount = (int)Math.Ceiling(total * 1.0 / pagesize);

                ViewBag.RealName = realname;
                ViewBag.SchoolCode = school;
                //上一页
                if (page - 1 > 0)
                    ViewBag.LastPage = page - 1;
                else
                    ViewBag.LastPage = 1;
                //下一页
                if (page + 1 > pagecount)
                    ViewBag.NextPage = pagecount;
                else
                    ViewBag.NextPage = page + 1;
                //最后页
                ViewBag.CurrPag = page;
                ViewBag.EndPage = pagecount;
                ViewBag.PageCount = pagecount;
                ViewBag.RecordCount = total;
                ViewBag.PageSize = pagesize;
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                if (sqlDataReader != null)
                {
                    sqlDataReader.Close();
                }

                sqlConnection.Close();
            }
            //默认改为当前用户学院
            ViewBag.School = DataAccess.getSelectList(connectionString, "Schools_Sel", "%", true);
            return View(Users);
        }

        //建立一般用户页面
        //get /admin/createuser
         [Authorize(Roles = "系统管理员")]
        public ActionResult UserCreate()
        {
            ViewBag.School = DataAccess.getSelectList(connectionString, "Schools_Sel", "01", false);
            return View();
        }
        //创建用户操作
        //POST /admin/createuser
        [HttpPost]
        [Authorize(Roles = "系统管理员")]
        public ActionResult UserCreate(CreatUserModel model)
        {
            if (ModelState.IsValid)
            {
                // 尝试注册用户
                MembershipCreateStatus createStatus;
                SqlConnection sqlConnection = new SqlConnection(connectionString);
                SqlCommand sqlCommand = new SqlCommand("Teacher_Ins", sqlConnection);
                sqlCommand.CommandType = CommandType.StoredProcedure;
                try
                {
                    Membership.CreateUser(model.UserName, model.Password, model.Email, null, null,true, null, out createStatus);

                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        Roles.AddUserToRole(model.UserName, "教师"); //增加基本教师权限
                        //在用户列表中添加新用户成功以后，在教师信息表中添加信息，失败的话删除注册信息
                        if (ModelState.IsValid)
                        {
                            sqlCommand.Parameters.Add("@teacherno", SqlDbType.NVarChar, 7).Value = model.UserName;
                            sqlCommand.Parameters.Add("@name", SqlDbType.NVarChar, 100).Value = model.RealName;
                            sqlCommand.Parameters.Add("@school", SqlDbType.NVarChar, 2).Value = model.School;
                            sqlCommand.Parameters.Add("@date", SqlDbType.DateTime).Value = DateTime.Now;
                            sqlCommand.Parameters.Add("@modifier", SqlDbType.NVarChar, 6).Value = User.Identity.Name;

                            sqlConnection.Open();
                            if (sqlCommand.ExecuteNonQuery() == 1)
                            {
                                ModelState.AddModelError("", "添加用户成功");
                                return RedirectToAction("UserCreate", "Admin");
                            }
                            else
                            {
                                Membership.DeleteUser(model.UserName);
                                ModelState.AddModelError("", "添加用户失败");
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorCodeToString(createStatus));
                    }
                }
                catch (SqlException e)
                {
                    throw e;
                }
                finally
                {
                    sqlConnection.Close();
                }
            }
            ViewBag.School = DataAccess.getSelectList(connectionString, "Schools_Sel", "01", false);
            return View(model);
        }

        [Authorize(Roles = "系统管理员")]
        public ActionResult UserDetail(string UserName)
        {

            SqlConnection sqlConnection = new SqlConnection(connectionString);
            SqlCommand sqlCommand = new SqlCommand("Teacher_Sel", sqlConnection);
            sqlCommand.CommandType = CommandType.StoredProcedure;
            SqlDataReader sqlDataReader = null;
            try
            {
                sqlCommand.Parameters.Add("@teacherno", SqlDbType.NVarChar, 7).Value = UserName;
                sqlConnection.Open();
                sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);

                if (sqlDataReader.HasRows)
                {
                    sqlDataReader.Read();
                    UserDetailModel userDetail = new UserDetailModel();
                    ;
                    userDetail.UserName = UserName;
                    userDetail.RealName = sqlDataReader["Name"].ToString();
                    userDetail.School= sqlDataReader["School"].ToString();
                    string [] _roles=Roles.GetRolesForUser(UserName);
                    string temprole = "";
                    for (int i = 0; i < _roles.Length; i++)
                        temprole += _roles[i]+",";

                    userDetail.Roles = temprole.Substring(0, temprole.Length - 1);

                    return View(userDetail);
                }
                else
                {
                    //返回错误信息。
                }

            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                if (sqlDataReader != null) { sqlDataReader.Close(); }
            }
            return Content("检索失败");
        }

         [Authorize(Roles = "系统管理员")]
        public ActionResult UserEdit(string userName)
        {
            ChangePasswordModel change = new ChangePasswordModel();
            change.UserName = userName;
            return View(change);
        }
         [HttpPost]
         [Authorize(Roles = "系统管理员")]
         public ActionResult UserEdit(ChangePasswordModel model)
         {
             model.OldPassword = "1";
             if (ModelState.IsValid)
             {

                 // 在某些出错情况下，ChangePassword 将引发异常，
                 // 而不是返回 false。
                 bool changePasswordSucceeded;
                 try
                 {
                     MembershipUser currentUser = Membership.GetUser(model.UserName, true );
                     string p = currentUser.ResetPassword();
                     changePasswordSucceeded=currentUser.ChangePassword(p, model.NewPassword);
                 }
                 catch (Exception)
                 {
                     changePasswordSucceeded = false;
                 }

                 if (changePasswordSucceeded)
                 {
                     return RedirectToAction("ChangePasswordSuccess", "Account");
                 }
                 else
                 {
                     ModelState.AddModelError("", "当前密码不正确或新密码无效。");
                 }
             }

             // 如果我们进行到这一步时某个地方出错，则重新显示表单
             return View(model);
         }
        #region Membership错误代码解析
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // 请参见 http://go.microsoft.com/fwlink/?LinkID=177550 以查看
            // 状态代码的完整列表。
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "用户名已存在。请输入不同的用户名。";

                case MembershipCreateStatus.DuplicateEmail:
                    return "该电子邮件地址的用户名已存在。请输入不同的电子邮件地址。";

                case MembershipCreateStatus.InvalidPassword:
                    return "提供的密码无效。请输入有效的密码值。";

                case MembershipCreateStatus.InvalidEmail:
                    return "提供的电子邮件地址无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidAnswer:
                    return "提供的密码取回答案无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidQuestion:
                    return "提供的密码取回问题无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidUserName:
                    return "提供的用户名无效。请检查该值并重试。";

                case MembershipCreateStatus.ProviderError:
                    return "身份验证提供程序返回了错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                case MembershipCreateStatus.UserRejected:
                    return "已取消用户创建请求。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                default:
                    return "发生未知错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";
            }
        }
        #endregion
    }
}
